package com.huizhe.common.result;

import lombok.Data;
import org.springframework.util.StringUtils;

import java.util.Objects;

@Data
public class Result<T> {
    private Integer code;
    private String message;
    private T data;

    public Result() {
    }

    private Result(int code) {
        this.code = code;
        this.message = ResultCode.getMessage(code);
    }

    private Result(int code, T data) {
        this.code = code;
        this.message = ResultCode.getMessage(code);
        this.data = data;
    }

    private Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    private Result(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public static <T> Result<T> createBySuccess() {
        return new Result(ResultCode.SUCCESS.getCode());
    }

    public static <T> Result<T> createBySuccess(T data) {
        return new Result(ResultCode.SUCCESS.getCode(), data);
    }

    public static <T> Result<T> createBySuccess(String message, T data) {
        return new Result(ResultCode.SUCCESS.getCode(), message, data);
    }

    public static <T> Result<T> createFailure() {
        return new Result(ResultCode.FAILURE.getCode(), ResultCode.FAILURE.getMessage());
    }

    public static <T> Result<T> createFailure(ResultCode resultCode) {
        return new Result(resultCode.getCode(), resultCode.getMessage());
    }

    public static <T> Result<T> createFailure(String failureMessage) {
        if (StringUtils.isEmpty(failureMessage)) {
            return createFailure();
        } else {
            try {
                return new Result(ResultCode.valueOf(failureMessage).getCode(), failureMessage);
            } catch (Exception var2) {
                return new Result(ResultCode.FAILURE.getCode(), failureMessage);
            }
        }
    }

    public static <T> Result<T> createFailure(int failureCode, String failureMessage) {
        return new Result(failureCode, failureMessage);
    }

    public boolean isSuccess() {
        return Objects.equals(this.code, ResultCode.SUCCESS.getCode());
    }

}
